package com.shallowdream.threaddemo.thread;

import java.io.IOException;
import java.io.RandomAccessFile;

public class Demo {
    /**
     * 多线程文件拷贝
     * @param srcPath：源路径
     * @param DestPath：目标地址
     * @param ThreadNum：线程数量
     */
    public static void MutilThreadCopyFile(String srcPath, String DestPath, Integer ThreadNum) {
        RandomAccessFile read=null;
        RandomAccessFile read1=null;
        try{
            read=new RandomAccessFile(srcPath,"r");
            read1=new RandomAccessFile(DestPath,"r");
            long length=read.length();
            long num=length/ThreadNum; //可能会精度损失，因此最后启动的线程其终止位置最好采用源文件长度
            for(int i=0 ;i<ThreadNum ;i++){
                ThreadDemo threadDemo=new ThreadDemo(i==0 ? 0 : num*i+1 ,i==ThreadNum-1 ? length : num*(i+1),srcPath,DestPath);
                System.out.println(threadDemo.getName());
                System.out.println(num);
                threadDemo.start();
            }
            System.out.println(check(read,read1));
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /*
     * @Description : 检查两个文件的数据是否一致；
     * @param file1
     * @param file2
     * @return :   boolean
     */
    private static boolean check(RandomAccessFile file1,RandomAccessFile file2)throws IOException {
        int num1=-1;
        int num2=-1;
        while(((num1=file1.read())!=-1)&((num2=file2.read())!=-1)){
            if(num1!=num2 )
                return false;
        }
        if (num1!=-1||num2!=-1)
            //注意：上面while循环不能用&& 因为如果前面的等于-1；
            //&&后面的就不会执行，num2就保存的是旧值；
            return false;
        return true;
    }
    public static void main(String[] args) {
        MutilThreadCopyFile("E:\\resource\\11.msi",
                "E:\\ceshi\\111.msi",10);
    }


}
